//
//  SReadViewController.m
//  News
//
//  Created by dlios on 15-5-13.
//  Copyright (c) 2015年 PEAK. All rights reserved.
//

#import "SReadViewController.h"
#import "SYueduyijiViewController.h"
#import "STianjiaViewController.h"
#import "SYueduViewController.h"
#import "SReadtableView.h"
#import "SYuduTableViewCell.h"
#import "SyoudaTableViewCell.h"
#import "SNetWorkHandle.h"
#import "SRead.h"
#import "SZuodaTableViewCell.h"
#import "SWenziTableViewCell.h"
#import "MJRefresh.h"
#import "MJRefreshConst.h"
@interface SReadViewController ()<UITableViewDataSource, UITableViewDelegate>

//建立页码控制器属性
@property (nonatomic, retain) UISegmentedControl *seg;
@property (nonatomic, assign) NSInteger segzhi;
@property (nonatomic, retain) SReadtableView *tableView;
//存有SRead的数组
@property (nonatomic, retain) NSMutableArray *readArr;

//接收通知中心传过来的内容
@property (nonatomic, retain) NSMutableArray *arr;

@property(nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property(nonatomic, retain) UIAlertView *al;

@property(nonatomic, retain) UIImageView *imageView;

@end

@implementation SReadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    //self.tabBarController.tabBar.tintColor = [UIColor redColor];
   
    self.readArr = [NSMutableArray array];
    
    //在一级页面写该方法   可以改变下一界面导航栏title颜色
    self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor], UITextAttributeFont:[UIFont boldSystemFontOfSize:20]};
    
    

    self.navigationController.navigationBar.translucent = NO;

    self.automaticallyAdjustsScrollViewInsets = NO;
  
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-icon01"] style:UIBarButtonItemStylePlain target:self action:@selector(tianjiadingyue)];
       [self yemakongzhiqi];
    [self jianlitableView];
    //请求出现小菊花
    self.imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    _imageView.image = [UIImage imageNamed:@"5EA2D64D-15BE-43D8-AB18-E15BCE039C8F"];
    _imageView.tag = 1000;
    [_imageView setBackgroundColor:[UIColor blackColor]];
    _imageView.alpha = 1;
    [self.view addSubview:_imageView];
    [_imageView release];
    
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [_activityIndicator setCenter:_imageView.center];
    [_activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [_imageView addSubview:_activityIndicator];
    
    [_activityIndicator startAnimating];
    
    //先默认下拉
    self.isUpLoading = NO;
    //集成上啦下拉功能
    [NetworkHandle startNetMonitoringWithCompletion:^(id result) {
        NSString *str = [result objectForKey:@"info"];
        if ([str isEqualToString:@"WIFI就是爽,上网不花钱!"]|| [str isEqualToString:@"流量多风险,上网需谨慎!"]) {
           
            
            [self addHeader];
            [self addFooter];
        }else{
            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:[result objectForKey:@"info"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [al show];
//            self.al = [[UIAlertView alloc] initWithTitle:@"提示" message:[result objectForKey:@"info"] delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//            [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(xiaoshi) userInfo:nil repeats:NO];
//            [_al show];
            
          
            
        }
    }];
    
    
    
    
    
    
}
//用于取消提示窗
- (void)xiaoshi
{
    [_al dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - 下拉刷新
- (void)addHeader
{
    __block SReadViewController *vc = self;
    
    //添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        
        vc.isUpLoading = NO;//标记为下拉操作
        [vc getData];//重新请求数据
        
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
}

#pragma mark - 上啦加载更多
- (void)addFooter
{
    __block SReadViewController *vc = self;
    //添加上啦刷新尾部控件
    [self.tableView addFooterWithCallback:^{
       //进入刷新状态就会回调这个block
        vc.isUpLoading = YES; //标记为上啦操作
        [vc getshangla];
    }];
}

/**
 *  获取数据
 *
 *  @return
 */
- (void)getData;
{
    // 参数1: 网络接口
    // 参数2: 返回数据的Block 参数result中是网络请求的返回数据
    [SNetWorkHandle getDataWithURL:@"http://c.3g.163.com/recommend/getSubDocPic?passport=&devId=AFBF8E4D-DAF7-4899-9657-5FE0F6825D11&size=20&from=yuedu" completion:^(id result) {
        // result为请求接口的返回数据
        //用字典接收
        NSMutableDictionary *dic = result;
        
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.readArr removeAllObjects];
        }

        NSMutableArray *arr = [dic objectForKey:@"推荐"];
        //遍历数组
        
        for (NSMutableDictionary *temp in arr) {
            SRead *read = [[SRead alloc] initWithDic:temp];
            
            [self.readArr addObject:read];
            
          
        }
       // [self.tableView footerEndRefreshing];//结束底部刷新效果
        [self.tableView headerEndRefreshing];//结束头部刷新效果
        //刷新tableview
        [self.tableView reloadData];
        //NSLog(@"%@", _readArr);
        
        [_imageView removeFromSuperview];
    }];
    

}

//上拉加载更多获取数据
- (void)getshangla
{
    [SNetWorkHandle getDataWithURL:@"http://c.3g.163.com/recommend/getSubDocNews?passport=09e9efd93a50e97408faffd7003b0db2@tencent.163.com&devId=866152020415149&size=20&from=yuedu" completion:^(id result) {
        
        
        // result为请求接口的返回数据
        //用字典接收
        NSMutableDictionary *dic = result;
        
        
        
        NSMutableArray *arr = [dic objectForKey:@"推荐"];
        //遍历数组
        
        for (NSMutableDictionary *temp in arr) {
            SRead *read = [[SRead alloc] initWithDic:temp];
            
            [self.readArr addObject:read];
        }
        [self.tableView footerEndRefreshing];//结束底部刷新效果
        //[self.tableView headerEndRefreshing];//结束头部刷新效果
        //刷新tableview
        [self.tableView reloadData];
        //NSLog(@"%@", _readArr);

        
        
    }];
}


/**
 *  点击按钮  push到添加页面
 */
- (void)tianjiadingyue
{
    STianjiaViewController *tianjia = [[[STianjiaViewController alloc] init] autorelease];
    [self.navigationController pushViewController:tianjia animated:YES];
}

/**
 *  视图控制器添加页码控制器
 */
- (void)yemakongzhiqi
{
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"阅读"]];
    _seg.frame = CGRectMake(100, 64, self.view.frame.size.width - 200, 30);
    //默认选中索引
    _seg.selectedSegmentIndex = 0;
    //渲染颜色
    _seg.tintColor = [UIColor whiteColor];
    [_seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
      self.navigationItem.titleView = _seg;
    
    [_seg release];

}
//页码控制器响应方法
- (void)segAction:(UISegmentedControl *)seg
{
    self.segzhi = seg.selectedSegmentIndex;
    
    //点击时让tableView重新加载数据
    [_tableView reloadData];
   
}

- (void)jianlitableView
{
    self.tableView = [[SReadtableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49 - 64) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    [_tableView release];
}
/**
 *  协议方法
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_readArr.count != 0) {
        
        return _readArr.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_segzhi == 0) {
        SRead *read = _readArr[indexPath.row];
        
        SYuduTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"str"];
        SZuodaTableViewCell *zuoda = [tableView dequeueReusableCellWithIdentifier:@"zuoda"];
        SyoudaTableViewCell *youda = [tableView dequeueReusableCellWithIdentifier:@"youda"];
        SWenziTableViewCell *wenzi = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        /**
         *  判段无三张图片是显示当前cell
         */
        if (read.imgnewextra.count == 0 && read.img.length != 0) {
            
            
            if (cell == nil) {
                cell = [[SYuduTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"str"];
            }
            
            cell.read = read;
            
            return cell;
        }
        /**
         *  有三张图片的cell左面显示大的
         */
        if (read.imgnewextra.count != 0 && [read.Stemplate isEqualToString:@"pic31"]) {
            
            if (youda == nil) {
                youda = [[SyoudaTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"youda"];
            }
            youda.read = read;
            
            return youda;
            
        }
        if (read.imgnewextra.count != 0 && [read.Stemplate isEqualToString:@"pic32"]) {
            
            if (zuoda == nil) {
                
                zuoda = [[SZuodaTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"zuoda"];
            }
            zuoda.read = read;
            
            return zuoda;
        }
        else{
            
            if (wenzi == nil) {
                wenzi = [[SWenziTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
            }
            wenzi.read = read;
                       return wenzi;
        }
        
    }
       return nil;

}




//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     SRead *read = _readArr[indexPath.row];
    if (read.imgnewextra.count == 0 && read.img.length != 0) {
    return (self.view.frame.size.height - 49) / 3;
    
    }if (read.imgnewextra.count != 0){
        
        return ((self.view.frame.size.height - 49) / 3) *2;
    }
    
    else {
        return (self.view.frame.size.height - 49) / 3;
    }
   
    
}
//Cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_segzhi == 0) {
        
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SYueduViewController *yuedu = [[[SYueduViewController alloc] init] autorelease];
        
         SRead *read = _readArr[indexPath.row];
        yuedu.str = read.docid;
        
       
    
        
        [self.navigationController pushViewController:yuedu animated:YES];
    
    }
        
    
   
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
